#pragma once
#include <iostream>
#include <string>
#include "log.hpp"

using std::cout;
using std::endl;

extern log lg;

class Task
{
public:
    Task(int acfd, const std::string &ipbuffer, const uint16_t &client_port)
        : _acfd(acfd), _client_ip(ipbuffer), _client_port(client_port)
    {
    }

    ~Task()
    {
    }

    void run()
    {
        char buffer[4096];
        while (true)
        {
            ssize_t n = read(_acfd, buffer, sizeof(buffer));
            if (n > 0) // 读取成功
            {
                buffer[n] = 0; // 当做字符串
                // 客户端接收打印
                cout << "client say# " << buffer << endl;
                // 回显给客户端
                std::string echo_string = "tcp-server echo# ";
                echo_string += buffer;
                write(_acfd, echo_string.c_str(), echo_string.size());
            }
            else if (n == 0)
            {
                // 当客户端退出，意味着服务器没有任何数据可读，那么我们这里规定服务器也退出
                lg.logmessage(Info, "%s:%d quit, server close...", _client_ip.c_str(), _client_port);
                break;
            }
            else // n < 0
            {
                // 读取错误
                lg.logmessage(Warning, "server read error...");
                break;
            }
        }
    }

private:
    int _acfd;
    std::string _client_ip;
    uint16_t _client_port;
};